package com.bean;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Cc
 * 2024-03-29
 */
public class People<T> {
    private T pet;

    public People() {
    }

    public People(T pet) {
        this.pet = pet;
    }

    public T getPet() {
        return pet;
    }

    public void setPet(T pet) {
        this.pet = pet;
    }

    /**
     * 主人 带着 Pet 去逛街
     * 根据 反射 获取 Pet 的 属性方法
     * 判断宠物是否 温顺
     *
     * @throws NoSuchFieldException      没有这样字段例外
     * @throws IllegalAccessException    非法访问例外
     * @throws InvocationTargetException 调用目标异常
     */
    public void shopPing() throws NoSuchFieldException, IllegalAccessException, InvocationTargetException {
        Class<?> petClass = pet.getClass();

        if (!(pet instanceof Docile)) {
            System.out.println("不能带不温顺的宠物逛街");
            return;
        }

        Field field = petClass.getDeclaredField("name");

        field.setAccessible(true);

        Object petName = field.get(pet);

        System.out.println("主人带着" + petName + "去逛街");

        try {
            Method callMethod = petClass.getDeclaredMethod("call");
            callMethod.invoke(pet);
        } catch (NoSuchMethodException e) {
            System.out.println(petName + "在乱叫");
        }
    }
}
